package com.example.myapplication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "hello";
    private TextView mSend_text;
    private TextView mSend_text_dis;
    private TextView receive_info,receive_temp,receive_humi,receive_smoke,receive_human,receive_voice;
    private Button mBtn_send,mBtn_state_change;
    private Socket mSocket;
    private PrintStream out;
    private ConnectThread mConnectThread;
    private String mip = "192.168.4.1";
    private int mport = 8089;
    private Button mBtn_turn;
    private BufferedReader mBufferedReader;
    private String readStrng;
    private String tempStrng;
    private myHandler mHandler = new myHandler();
    private Timer mTimer;
    private ReceiveDataTask mReceiveDataTask;
    private EditText mText_ip;
    private EditText mText_port;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    @Override
    protected void onStart() {
        super.onStart();
        startTimer();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTimer();
    }

    private class myHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1212:
                    /*
                       1、得到信息首字母为0时为温湿度传感器
                       2、得到信息首字母为1时为声音传感器
                       3、得到信息首字母为2时为mq2传感器
                       4、得到信息首字母为3时为人体红外传感器
                    */
                    receive_info.setText(readStrng);
                    switch (readStrng.charAt(0)){
                        case '0':
                            receive_temp.setText("温度："+readStrng.substring(6,12)+"℃");
                            receive_humi.setText("湿度："+readStrng.substring(19)+"%");
                            break;
                        case '1':
                            receive_voice.setText(receive_voice.getText()+"\n"+new Date()+"有声音");
                            break;
                        case '2':
                            receive_smoke.setText(receive_smoke.getText()+"\n"+new Date()+"有烟雾");
                            break;
                        case '3':
                            receive_human.setText(receive_human.getText()+"\n"+new Date()+"有人经过");
                            break;
                        default:
                            break;
                    }
//                    mSend_text_dis.setText(readStrng.substring(1,11)+"℃\n"+readStrng.substring(12)+"%");
                    break;
            }
        }
    }

    private void initView() {
        mSend_text_dis = findViewById(R.id.send_text_dis);
        mSend_text = findViewById(R.id.send_text);
        mBtn_state_change = findViewById(R.id.btn_state_change);
        mBtn_send = findViewById(R.id.btn_send);
        mBtn_turn = findViewById(R.id.btn_turn);
        mText_ip = findViewById(R.id.edit_ip);
        mText_port = findViewById(R.id.edit_port);

        receive_human=findViewById(R.id.receive_human);
        receive_temp=findViewById(R.id.receive_temp);
        receive_humi=findViewById(R.id.receive_humi);
        receive_info=findViewById(R.id.receive_info);
        receive_smoke=findViewById(R.id.receive_smoke);
        receive_voice=findViewById(R.id.receive_voice);

        mBtn_send.setOnClickListener(this);
        mBtn_turn.setOnClickListener(this);
        mBtn_state_change.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_turn:
                if (mSocket == null || !mSocket.isConnected()) {
                    if(!TextUtils.isEmpty(mText_ip.getText()) && !TextUtils.isEmpty(mText_port.getText())){
                        mip = mText_ip.getText().toString();
                        mport = Integer.parseInt(mText_port.getText().toString());
                        Log.i(TAG, "onClick: "+mport);
                        mConnectThread = new ConnectThread(mip, mport);
                        mConnectThread.start();
                    }else if(TextUtils.isEmpty(mText_ip.getText())){
                        Toast.makeText(this,"请输入IP地址", Toast.LENGTH_SHORT).show();
                    }else if(TextUtils.isEmpty(mText_port.getText())){
                        Toast.makeText(this,"请输入端口号", Toast.LENGTH_SHORT).show();
                    }
                }
                if (mSocket != null && mSocket.isConnected()) {
                    try {
                        mSocket.close();
                        mSocket = null;
                        mBtn_turn.setText("连接");
                        Toast.makeText(this, "连接已断开", Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.btn_send:
                final String str = mSend_text.getText().toString();
                if (str != null && out != null) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            out.print(str);
                            out.flush();
                        }
                    }).start();

                }
                break;
            case R.id.btn_state_change:
                Log.i(TAG, "onChange: "+mport);
                if ( out != null) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            out.print("4");
                            out.flush();
                        }
                    }).start();
                    if(mBtn_state_change.getText().equals("夜间模式")){
                        mBtn_state_change.setText("白天模式");
                    }else{
                        mBtn_state_change.setText("夜间模式");
                    }

                }
                break;

        }
    }

    private class ConnectThread extends Thread {
        private String ip;
        private int port;
        public ConnectThread(String ip, int port) {
            this.ip = ip;
            this.port = port;
        }
        @Override
        public void run() {
            try {
                mSocket = new Socket(ip, port);
                out = new PrintStream(mSocket.getOutputStream());
                mBufferedReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mBtn_turn.setText("断开");
                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }


    private class ReceiveDataTask extends TimerTask {
        @Override
        public void run() {
            try {
                if (mBufferedReader != null && (mBufferedReader.ready())) {
                    char[] readbuff = new char[30];
                    byte[] readByte = new byte[30];
                    mBufferedReader.read(readbuff, 0, readbuff.length);
                    tempStrng = String.valueOf(readbuff);
                    readByte = tempStrng.getBytes();
                    readStrng = new String(readByte, 0, readByte.length, "GB2312");
                    Message message = Message.obtain();
                    message.what = 1212;
                    mHandler.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private void startTimer() {
        Log.i(TAG, "startTimer:");
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mReceiveDataTask == null) {
            mReceiveDataTask = new ReceiveDataTask();
        }
        mTimer.schedule(mReceiveDataTask, 0, 10);
    }

    private void stopTimer() {
        Log.i(TAG, "stopTimer: ");
        if (mReceiveDataTask != null) {
            mReceiveDataTask.cancel();
            mReceiveDataTask = null;
        }
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }
}
